<template>
  <div id="app">
    <div class="ddloading" v-if="!isLogin">
      <no-data v-if="loadingtxt" :desc="loadingtxt"></no-data>
    </div>
    <transition name="slide">
      <template v-if="isLogin">
        <keep-alive v-if="$route.meta.keepAlive">
          <router-view></router-view>
        </keep-alive>
        <router-view v-else></router-view>
      </template>
    </transition>
  </div>
</template>
<script>
import NoData from '@/components/NoData'
import { parseTime } from '@/utils/index'
import { ddLogin, queryAppData } from '@/api/home'
import { removeWatermark, setWaterMark } from '@/utils/watermark'
import sensormixin from '@/mixins'

const IS_PROD = ['production', 'prod'].includes(process.env.VUE_APP_ENV)

export default {
  name: 'App',
  mixins: [sensormixin],
  components: { NoData },
  data() {
    return {
      isLogin: false,
      dpToken: '',
      loadingtxt: '',
      logs: [],
      loginfail: false
    }
  },
  created() {
    if (this.$isDD) {
      this.$dd.ui.webViewBounce.disable()
    }
    this.$router.onReady(() => {
      if (['Home', 'TraceDetail'].includes(this.$route.name)) {
        if (this.$route.query.zt_token !== undefined && this.$route.query.zt_token != null) {
          this.dpToken = this.$route.query.zt_token
          // 拿到ticket 后调用鉴权接口
          this.getAuth().then(() => {
            this.oauthpush({ code: this.dpToken, url: location.href })
          })
        } else {
          this.loadingtxt = '暂无授权'
        }
      } else {
        if (this.$store.getters.ticket || this.$route.name === 'detail') {
          this.isLogin = true
          if (this.$store.getters.userInfo) {
            const user = this.$store.getters.userInfo
            this._setWaterMark(user.name, user.username)
          }
        } else {
          this.loadingtxt = '暂无权限'
        }
      }
      // && this.$route.query.quickenter === 'now'
      if (!this.$isDD && !IS_PROD) {
        // 非钉钉环境之间测试
        this.isLogin = true
      }
    })
  },
  destroyed() {
    removeWatermark()
  },
  methods: {
    async oauthpush(data) {
      const { value, success } = await queryAppData(data)
      if (success) {
        console.log('value', value, '>>>>')
        value.type = 0
        value.jsApiList = [
          'runtime.info',
          'biz.contact.choose',
          'device.notification.confirm',
          'device.notification.alert',
          'device.notification.prompt',
          'biz.ding.post',
          'biz.util.openLink',
          'biz.contact.complexPicker'
        ]
        const { corpId, agentId } = value
        console.log('value', corpId, agentId, '>>>>')
        this.$store.commit('SET_CORPID', corpId)
        this.$store.commit('SET_APPID', agentId)
        this.$dd.config(value)
      }

      this.$dd.error(function(err) {
        alert('dd error: ' + JSON.stringify(err))
        console.log('dd error: ' + JSON.stringify(err))
      }) // 该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题
    },
    _setWaterMark(name, username) {
      setWaterMark(`${name || ''} ${username || ''} ${parseTime(new Date(), '{y}-{m}-{d}')}`)
    },
    updateLogin(e) {
      this.isLogin = e
    },
    handleForceLogin() {
      this.isLogin = true
    },
    async getAuth() {
      const res = await ddLogin({ code: this.dpToken })
      if (res && res.value && res.value.ticket) {
        this.$store.commit('SET_TICKET', res.value.ticket)
        const { username, name, userid, avatar } = res.value
        this.$store.commit('SET_USERINFO', { username, name, userid, avatar })
        this.isLogin = true
        this._setWaterMark(name, username)
        username && this.sensorlogin(username)
      } else {
        this.$toast.fail('获取授权失败')
        this.loadingtxt = '获取授权失败'
        this.loginfail = true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
#app {
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  background-color: #292e3a;
}
.ddloading {
  height: 100vh;
  width: 100%;
  .van-loading {
    margin-bottom: 20px;
    max-width: 80%;
    .van-loading__text {
      white-space: pre-wrap;
      word-break: break-word;
      color: #ffffff99;
    }
  }
}
.slide-enter-active {
  transition: all 0.5s ease;
}
.slide-leave-active {
  transition: all 0.1s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-enter, .slide-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */ {
  // transform: translateX(10px);
  opacity: 0;
}
</style>
